package com.raymond.http;

import com.raymond.http.netty.HttpAddress;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.*;

import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author :  raymond
 * @version :  V1.0
 * @date :  2021-12-11 18:45
 */
public class HttpClientUtil {

    public static HttpRequest getHttpRequest(String url) {
        return new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, url);
    }

    public static HttpRequest postHttpRequest(String url) {
        return postHttpRequest(url, null);
    }

    public static HttpRequest postHttpRequest(String url, String message) {
        return postHttpRequest(url, message);
    }

    public static HttpRequest postHttpRequest(String url, String message, Map<String, String> headers) {
        return postHttpRequest(url, message, headers, StandardCharsets.UTF_8);
    }
    
    public static HttpRequest postHttpRequest(String url, String message, Map<String, String> headers, Charset charset) {
        DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                HttpMethod.POST, url, message == null ? Unpooled.buffer(0) : Unpooled.wrappedBuffer(message.getBytes(charset)));
        request.headers().set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());
        URI uri = URI.create(url);
        request.headers().set(HttpHeaderNames.HOST, uri.getHost() + ":" + uri.getPort());
        //其他头部信息
        if (headers != null && !headers.isEmpty()) {
            headers.forEach((k, v) -> request.headers().set(k, v));
        }
        return request;
    }
}
